package com.tarim.streetdance.util;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class AESUtils {

    public static void main(String[] args) throws Exception {
        String clearPwd = "19980921gwh";
//        clearPwd = "dmBvknvOQNOfg0T0u1swqA==";
        // 密码加密后的密文
        /*String encryptedPwd = Encrypt(clearPwd);
        System.out.println(encryptedPwd);
        System.out.println(encryptedPwd.length());*/
        // 解密后的字符串
        String decryptedPwd = Decrypt("ayU3oX8f0P3safo8QZbU5g==");
        System.out.println(decryptedPwd);

    }

    // 日志
    private static final Logger logger = LoggerFactory.getLogger(AESUtils.class);
    private static  String sKey = "street_dance";//秘钥种子
    // 加密
    public static String Encrypt(String sSrc) {
        // 判断Key是否正确
        if (sKey == null) {
            return null;
        }
        try {
            byte[] raw = getRawKey(sKey.getBytes());
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
            return new Base64().encodeToString(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    // 解密
    public static String Decrypt(String sSrc){
        try {
            // 判断Key是否正确
            if (sKey == null) {
                return null;
            }
            byte[] raw = getRawKey(sKey.getBytes());
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original,"utf-8");
                return originalString;
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
                return null;
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * @param seed 种子数据
     * @return 密钥数据
     */
    private static byte[] getRawKey(byte[] seed) {
        byte[] rawKey = null;
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(seed);
            // AES加密数据块分组长度必须为128比特，密钥长度可以是128比特、192比特、256比特中的任意一个
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            rawKey = secretKey.getEncoded();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return rawKey;
    }
}

